package com.xutils;

import java.util.HashMap;
import java.util.Map;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.Presence;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.xutils.xmpp.callback.XmppCallBack;

public class XmppUtils {
	
	private static final String XMPP_RESOURCES = "Android";

	private XMPPConnection xmppConnection;	// XMPP链接
	
	private XmppCallBack callBack;	// 回调
	
	private static XmppUtils instance;
	
	private Map<String, Chat> chatManage = new HashMap<String, Chat>();	// 聊天窗口管理map集合 

	/////////////////////////////////////////////// create /////////////////////////////////////////////////////

	public static XmppUtils getInstance() {
		if( instance == null ) {
			instance = new XmppUtils();
		}
		
		return instance;
	}
	
	private XmppUtils() {
		
	}
	
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			switch (msg.what) {
			case 0:
				if( callBack != null ) {
					callBack.onStart();
				}
				break;
			case 1:
				if( callBack != null ) {
					callBack.onSuccess("login success");
				}
				break;
			case 2:
				closeConnection();
				if( callBack != null ) {
					callBack.onFailure(0, "login XMPPException error");
				}
				break;
			case 3:
				if( callBack != null ) {
					callBack.onFinish();
				}
				break;
			default:
				break;
			}
		}
		
	};
	
	/////////////////////////////////////////////// send /////////////////////////////////////////////////////
	
	public void login(final String ip, final int port, final String userId, final String pwd, final XmppCallBack callBack) {
		this.callBack = callBack;
		handler.sendEmptyMessage(0);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					getConnection(ip, port).login(userId, pwd, XMPP_RESOURCES);

					Presence presence = new Presence(Presence.Type.available);
					getConnection(ip, port).sendPacket(presence);

					handler.sendEmptyMessage(3);
					handler.sendEmptyMessage(1);
				} catch (XMPPException e) {
					handler.sendEmptyMessage(2);
					handler.sendEmptyMessage(3);
					e.printStackTrace();
				}

			}
		}).start();
	}
	
	public void logout() {
		closeConnection();
	}
	
	/**
	 * 得到Xmpp连接对象
	 * @return
	 */
	public XMPPConnection getXmppConnection() {
		return xmppConnection;
	}
	
	/** 
	 * 获取或创建聊天窗口 
	 * @param friend 好友名 
	 * @param listenter 聊天监听器
	 * @return 
	 */  
	public Chat getFriendChat(String friend, MessageListener listenter) {
	    if( xmppConnection == null ) {
	    	return null;
	    }
	    /** 判断是否创建聊天窗口 */
	    for (String fristr : chatManage.keySet()) {
	        if (fristr.equals(friend)) {
	            // 存在聊天窗口，则返回对应聊天窗口
	            return chatManage.get(fristr);
	        }
	    }
	    /** 创建聊天窗口 */
	    Chat chat = xmppConnection.getChatManager().createChat(friend + "@" + xmppConnection.getServiceName(), listenter);
	    /** 添加聊天窗口到chatManage */
	    chatManage.put(friend, chat);
	    return chat;
	}

    /**
     * 添加好友 有分组
     * @param roster
     * @param userName
     * @param name
     * @return
     */
    public boolean addUser(Roster roster, String userName, String name) {
        try {
            roster.createEntry(userName, name, null);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 添加好友 有分组
     * @param roster
     * @param userName
     * @param name
     * @return
     */
    public boolean addUser(Roster roster, String userName, String name, String groupName) {
        try {
            roster.createEntry(userName, name, new String[] { groupName });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

//	/**
//	 * 得到一个回话管理实例
//	 * @return
//	 */
//	public ChatManager getChatManager() {
//		if( xmppConnection == null ) {
//			Log.d("xmpp", "xmppConnection==null");
//			return null;
//		}
//		
//		if( chatManager == null ) {
//			return chatManager = xmppConnection.getChatManager();
//		}
//
//		return chatManager;
//	}
	
	/**
	 * 从会话管理实例中创建一个会话
	 * @param cm
	 * @param fromUserAccount
	 * @param listener
	 * @return
	 */
	public Chat createChat(ChatManager cm, String fromUserAccount, MessageListener listener) {
		if( cm != null ) {
			return cm.createChat(fromUserAccount, listener);
		}
		
		return null;
	}
	
	/**
	 * 添加一个聊天的监听
	 * @param cm
	 * @param listener
	 */
	public void addChatListener(ChatManager cm, ChatManagerListener listener) {
		if( cm != null ) {
			cm.addChatListener(listener);
		}
	}
	
	/////////////////////////////////////////////// Connection /////////////////////////////////////////////////////
	
	/**
	 * 获取连接
	 * 
	 * @return
	 */
	public XMPPConnection getConnection(String ip, int port) throws XMPPException {
		if (xmppConnection == null) {
			// 获取连接
			ConnectionConfiguration connConfig = new ConnectionConfiguration(ip, port);
			xmppConnection = new XMPPConnection(connConfig);
			xmppConnection.connect();
		}
		return xmppConnection;
	}
	
	/**
	 * 断开连接
	 */
	private void closeConnection() {
		if( xmppConnection != null ) {
			xmppConnection.disconnect();
			xmppConnection = null;
		}else{
			Log.d("xmpp", "xmppConnection==null");
		}
	}

}
